package top.smallway.lightbandassistant_app.method;

import static top.smallway.lightbandassistant_app.network.Okhttp.getHash;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import top.smallway.lightbandassistant_app.data.AppInfo;
import top.smallway.lightbandassistant_app.data.Competition_info;
import top.smallway.lightbandassistant_app.data.List_Data;
import top.smallway.lightbandassistant_app.data.Song_Data;

public class Method {

    /**
     * @param folderPath
     * @return turn为存在，false为不存在
     * @作者 小白
     * @说明 该方法为传入一个String格式的路径，用来判断是否存在该文件
     */
    private static boolean isFolderExists(String folderPath) {
        File folder = new File(folderPath);
        return folder.exists() && folder.isDirectory();
    }

    /**
     * @param context
     * @return ture为正常，false为不正常
     * @作者 小白
     * @说明 用于检查网络是否正常
     */
    private static boolean checkEnable(Context context) {
        NetworkInfo localNetworkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return (localNetworkInfo != null) && (localNetworkInfo.isAvailable());
    }

    /**
     * @param context
     * @return 返回值为String，返回当前的版本号
     * @作者 小白
     * @说明 该方法为获取当前应用的版本号，需要传入一个当前类（this或其他）
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            Log.e("版本号获取失败", "错误信息： ", e);
            return "获取版本号失败";
        }
    }


    /**
     * @param packageManager
     * @return Ture则为存在，false则为不存在
     * @作者 小白
     * @说明 使用前需要创建一个packageManager，该函数用于检查是否存在光之乐团游戏，通过检查是否存在该包名
     */
    public static boolean check(@NonNull PackageManager packageManager) {
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo("com.StarRiverVR.LightBand", PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * @param str
     * @return KEY或原值
     * @说明 传入字符串，并对其进行检查，若为代码搜索，则返回对应的key，若为歌名，则返回歌名。
     * @作者 小白
     */
    @NonNull
    public static String checkAndExtract(String str) {
        if (str == null) {
            return "";
        }

        String target = "!bsr ";
        if (str.startsWith(target)) {
            return str.substring(target.length());
        }
        return str;
    }

    public static boolean extract(String str) {
        String target = "!bsr ";
        return str.startsWith(target);
    }

    /**
     * 请求接口后，解析出对应的歌曲ID，歌曲名称，歌曲作者，谱师，歌曲介绍，下载地址，封面地址，音频地址，音频BPM，难度汇总
     *
     * @param response
     * @return 返回一个Song_Data格式的列表
     * @作者 小白
     * @时间 2023年10月31日 00点03分
     */
    public static List<Song_Data> unmarshalSongDataList(String response) {
        List<Song_Data> songList = new ArrayList<>();

        try {
            JSONObject jsonObject = JSON.parseObject(response);
            JSONArray docsArray = jsonObject.getJSONArray("docs");
            if (docsArray.isEmpty()) {
                return new ArrayList<>();
            }
            for (int i = 0; i < docsArray.size(); i++) {
                JSONObject docObject = docsArray.getJSONObject(i);
                Song_Data song = internalAnalysisJsonObject(docObject);
                songList.add(song);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return songList;
    }


    public static Song_Data unmarshalSongData(String response) {

        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.getString("error") != null) {
            return null;
        }

        return internalAnalysisJsonObject(jsonObject);
    }

    private static Song_Data internalAnalysisJsonObject(JSONObject jsonObject){
        List<String> diffs = new ArrayList<>();
        JSONObject blocks = new JSONObject();
        String id = jsonObject.getString("id");
        String songName = jsonObject.getString("name");
        String songAuthorName = jsonObject.getJSONObject("metadata").getString("songAuthorName");
        String levelAuthorName = jsonObject.getJSONObject("metadata").getString("levelAuthorName");
        String description = jsonObject.getString("description");
        String downloadURL = jsonObject.getJSONArray("versions").getJSONObject(0).getString("downloadURL");
        String songPicURL = jsonObject.getJSONArray("versions").getJSONObject(0).getString("coverURL");
        String previewURL = jsonObject.getJSONArray("versions").getJSONObject(0).getString("previewURL");
        String hash = jsonObject.getJSONArray("versions").getJSONObject(0).getString("hash");
        JSONArray collaborators = jsonObject.getJSONArray("collaborators");
        if (collaborators == null) {
            JSONObject jsonObject1 = jsonObject.getJSONObject("uploader");
            collaborators = new JSONArray();
            collaborators.add(jsonObject1);
        }


        Log.d("hash", previewURL);
        float bpm = jsonObject.getJSONObject("metadata").getFloat("bpm");
        int duration = jsonObject.getJSONObject("metadata").getInteger("duration");
        JSONArray diffsArray = jsonObject.getJSONArray("versions").getJSONObject(0).getJSONArray("diffs");
        for (int p = 0; p < diffsArray.size(); p++) {
            JSONObject diff = diffsArray.getJSONObject(p);
            int block = diff.getInteger("notes");
            String difficulty = diff.getString("difficulty");
            blocks.put(difficulty, block);
            diffs.add(difficulty);
        }
        Song_Data song = new Song_Data(id, songName, songAuthorName, levelAuthorName, description, downloadURL, songPicURL, previewURL, bpm, diffs, duration, blocks, hash, collaborators);

        return song;
    }


    public static List<List_Data> analysis_list(String response) {
        List<List_Data> list_data = new ArrayList<>();
        String name = null, time = null, URL = null, hash = null, num = null;
        List<List_Data> songList = new ArrayList<>();
        JSONObject jsonObj = JSON.parseObject(String.valueOf(response));
        JSONArray dataArray = JSON.parseArray(jsonObj.getString("data"));
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject obj = dataArray.getJSONObject(i);
            name = obj.getString("name");
            hash = obj.getString("hash");
            time = obj.getString("time");
            URL = obj.getString("URL");
            num = obj.getString("num");
            List_Data data = new List_Data(name, time, URL, hash, num);
            list_data.add(data);
        }

        return list_data;
    }


    /**
     * 秒转分钟:秒，传入Int格式的秒，返回String
     *
     * @param totalSeconds
     * @return
     */
    public static String secondsToTimeFormat(int totalSeconds) {
        int minutes = totalSeconds / 60; // 计算分钟数
        int remainingSeconds = totalSeconds % 60; // 计算剩余的秒数

        return String.format("%d:%02d", minutes, remainingSeconds);
    }

    /**
     * 在光团的目录中搜索（）的收藏.bplist文件。
     *
     * @return 找到的文件的绝对路径，如果没有找到则返回null。
     */
    public static String searchFileInDirectory() {
        String directoryPath = "/storage/emulated/0/Android/data/com.StarRiverVR.LightBand/files"; // 替换成你要搜索的目录路径
        String regex = "(?i).*收藏\\.bplist"; // 匹配以".bplist"为后缀的文件名的正则表达式
        Pattern pattern = Pattern.compile(regex);
        File dir = new File(directoryPath);
        File[] directoryListing = dir.listFiles();
//        return "/storage/emulated/0/测试文件.txt";
        if (directoryListing != null) {
            for (File child : directoryListing) {
                if (!child.isDirectory()) { // 添加条件判断，只处理文件，跳过目录
                    Matcher matcher = pattern.matcher(child.getName());
                    if (matcher.matches()) {
                        return child.getAbsolutePath(); // 返回找到的文件的绝对路径
                    }
                }
            }
        }

        return null; // 如果没有找到匹配的文件，则返回null
    }


    public static List<AppInfo> getAllInstalledApps(Context context) {
        List<AppInfo> appList = new ArrayList<>();
        PackageManager packageManager = context.getPackageManager();
        List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(0);

        for (ApplicationInfo app : installedApplications) {
            String appName = app.loadLabel(packageManager).toString();
            String packageName = app.packageName;
            appList.add(new AppInfo(appName, packageName));
        }

        return appList;
    }

    public static List<Competition_info> analysis_info(com.alibaba.fastjson2.JSONArray jsonArray) {
        List<Competition_info> infoList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String sort = jsonArray.getJSONObject(i).getString("sort");
            String player = jsonArray.getJSONObject(i).getJSONObject("player").getString("nickname");
            String score = jsonArray.getJSONObject(i).getString("score");
            infoList.add(new Competition_info(sort, player, score));
        }
        return infoList;
    }

    public static String getspeed(float duration, int block) {
        DecimalFormat df = new DecimalFormat("00.00");
        float speed = (float) block / duration;
        return df.format(speed);
    }

    public static String getandroidid(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public static boolean isValidEmail(String email) {
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static String gethash(String key) {
        final String url = "https://beatsaver.com/api/maps/id/" + key;
        String hash = getHash(url).getJSONArray("versions").getJSONObject(0).getString("hash");
        return hash + ".jpg";
    }


}


